import { ref } from 'vue'

export function useCategory() {
	const categoryList = ref([])
	const loading = ref(false)

	const loadCategories = async () => {
		try {
			loading.value = true

			// 关键修改：使用统一的API调用路径
			const response = await uni.$api.categoryApi.getCategoryList()
			// 根据您的数据结构调整
			if (response.statusCode === 200 && response.data.success) {
				const data = response.data.data
				console.log('✅ 获取到的分类数据:', data)
				categoryList.value = data
				return data
			} else {
				console.error('❌ 接口返回失败:', response.data.message)
				throw new Error(response.data.message || '获取分类失败')
			}
		} catch (error) {
			console.error('加载分类失败:', error)
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		} finally {
			loading.value = false
		}
	}

	const addNewCategory = async (categoryData) => {
		try {
			await uni.$api.categoryApi.addCategory(categoryData)
			await loadCategories()
		} catch (error) {
			console.error('添加分类失败:', error)
			throw error
		}
	}

	const updateCategoryData = async (id, categoryData) => {
		try {
			await uni.$api.categoryApi.updateCategory(id, categoryData)
			await loadCategories()
		} catch (error) {
			console.error('更新分类失败:', error)
			throw error
		}
	}

	const deleteCategoryData = async (id) => {
		try {
			await uni.$api.categoryApi.deleteCategory(id)
			await loadCategories()
		} catch (error) {
			console.error('删除分类失败:', error)
			throw error
		}
	}

	return {
		categoryList,
		loading,
		loadCategories,
		addNewCategory,
		updateCategory: updateCategoryData,
		deleteCategory: deleteCategoryData
	}
}